import React, { useState, useEffect } from 'react'
import { connect } from 'react-redux'

export const Cart = (props) => {
    const { cartList, setCartCount, setCartCheck, setAllCheckFun, deleteCart } = props;
    const allPrice = () => {
        return cartList.reduce((prev, next) => {
            return prev + (next.count * next.price)
        }, 0)
    }
    const [allCheck, setAllCheck] = useState(false)
    // useEffect(() => {
    // 调用reducer的全选方法
    // }, [allCheck]);
    return (
        <div>
            <input type="checkbox" checked={allCheck} onChange={({ target: { checked } }) => {
                setAllCheck(prev => {
                    return checked
                }); // 是一个异步
                setTimeout(() => {
                    setAllCheckFun(checked); // 全选
                })
            }}></input>
            {cartList.map((item, ind) => {
                return <div key={item.id}>
                    <input type="checkbox" checked={item.checked} onChange={({ target: { checked } }) => {
                        setCartCheck(item.id, checked);
                        setAllCheck(cartList.every(item => item.checked)); // 反选
                    }} />
                    {item.title}
                    <br />
                    {item.price}
                    <br />
                    <button
                        onClick={() => {
                            setCartCount(-1, item.id)
                        }}
                        disabled={item.count <= 1}
                    >-</button>
                    {item.count}
                    <button onClick={() => {
                        setCartCount(1, item.id)
                    }}>+</button>
                    <button onClick={() => {
                        deleteCart(item.id)
                    }}>
                        删除
                    </button>
                </div>
            })}
            总价： {allPrice()}
        </div>
    )
}

const mapStateToProps = (state) => ({
    ...state
})

const mapDispatchToProps = (dispatch) => {
    return {
        setCartCount: (num, id) => {
            dispatch({ type: "SET_CART_COUNT", data: { id, num } })
        },
        setCartCheck: (id, checked) => {
            dispatch({ type: "SET_CHECK", data: { id, checked } })
        },
        // 全选
        setAllCheckFun: (checked) => {
            dispatch({ type: "ALL_CHECK", data: { checked } })
        },
        // 删除
        deleteCart: (id) => {
            dispatch({ type: "DELETE_CART", data: { id } })
        }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Cart)
